package com.yusp75.mytorch

import android.Manifest
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresPermission
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat


class TorchService : Service() {
    private val cameraManager by lazy { getSystemService(CAMERA_SERVICE) as CameraManager }
    private var cameraId: String? = null
    private var isFlashOn = false

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        cameraId = cameraManager.cameraIdList.firstOrNull()
    }

    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            "com.yusp75.ACTION_START_TORCH" -> toggleFlash()
        }
        startForeground(1, buildNotification())
        return START_STICKY
    }

    @androidx.annotation.RequiresPermission(android.Manifest.permission.POST_NOTIFICATIONS)
    private fun toggleFlash() {
        cameraId?.let { id ->
            try {
                cameraManager.setTorchMode(id, !isFlashOn)
                isFlashOn = !isFlashOn
                updateNotification()
            } catch (e: CameraAccessException) {
                Log.e("TorchService", "Flash control failed", e)
            }
        }
    }

    @RequiresPermission(Manifest.permission.POST_NOTIFICATIONS)
    private fun updateNotification() {
        NotificationManagerCompat.from(this)
            .notify(1, buildNotification())
    }

    private fun buildNotification(): Notification {
        return NotificationCompat.Builder(this, "torch_channel")
            .setContentTitle("手电筒服务")
            .setContentText("手电已开启")
            .setSmallIcon(R.drawable.ic_torch)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setOngoing(isFlashOn)
            .setAutoCancel(isFlashOn)
            .build()
    }

    private fun createNotificationChannel() {
        NotificationChannel(
            "torch_channel",
            "手电筒服务",
            NotificationManager.IMPORTANCE_LOW
        ).also { channel ->
            getSystemService(NotificationManager::class.java)
                .createNotificationChannel(channel)
        }
    }

    override fun onDestroy() {
        cameraId?.let { cameraManager.setTorchMode(it, false) }
        super.onDestroy()
    }
}



